package bb.lanxing.calc.notify;

import android.content.Context;
import bb.lanxing.lib.devices.antplus.AntPlusDataDispatcher;
import bb.lanxing.lib.devices.base.converter.HeartrateConverter;
import bb.lanxing.lib.devices.utils.IHeartRateAlert;

public class HeartRateAlert extends HeartrateConverter
        implements IHeartRateAlert, AntPlusDataDispatcher.OnAntPlusHeartrateListener {
    private AlertControlDelegate alertControlDelegate;
    private int alertValued;
    private Context context;
    private boolean enabled;

    public HeartRateAlert(Context context, int sound) {
        this.context = context;
        this.alertControlDelegate = new AlertControlDelegate(context, sound);
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (this.enabled == enabled) {
            return;
        }
        this.enabled = enabled;
        if (enabled) {
            return;
        }
        AlertControlDelegate alertControlDelegate = this.alertControlDelegate;
        if (alertControlDelegate != null && alertControlDelegate.isPlaying()) {
            this.alertControlDelegate.stop();
        }
        VibratorHelper.cancel(this.context);
    }

    @Override
    public void setAlertValue(int value) {
        this.alertValued = value;
    }

    @Override
    public void onHeartrate(int deviceType, int heartrate) {
        if (this.enabled) {
            if (heartrate >= this.alertValued) {
                play();
            } else {
                stop();
            }
        }
    }

    @Override
    public void play() {
        if (this.enabled) {
            AlertControlDelegate alertControlDelegate = this.alertControlDelegate;
            if (alertControlDelegate != null && !alertControlDelegate.isPlaying()) {
                this.alertControlDelegate.play();
            }
            VibratorHelper.vibrate(this.context, VibratorHelper.VIBRATE_ALERT_PATTERN, 0);
        }
    }

    @Override
    public void stop() {
        AlertControlDelegate alertControlDelegate = this.alertControlDelegate;
        if (alertControlDelegate != null && alertControlDelegate.isPlaying()) {
            this.alertControlDelegate.stop();
        }
        VibratorHelper.cancel(this.context);
    }

    @Override
    public void release() {
        AlertControlDelegate alertControlDelegate = this.alertControlDelegate;
        if (alertControlDelegate != null) {
            alertControlDelegate.release();
            this.alertControlDelegate = null;
        }
        VibratorHelper.cancel(this.context);
    }
}
